#include "StdAfx.h"
#include "FileSplit.h"

LPBYTE LoadFile(LPCTSTR lpFileName, LPDWORD lpSize)
{
	BOOL ret;
	CFile file;
	DWORD size;
	LPBYTE buff;

	ret = file.Open(lpFileName, CFile::modeRead | CFile::shareDenyNone);
	if(!ret)
	{
		return NULL;
	}
	size = (DWORD)file.GetLength();
	if(size == 0)
	{
		return NULL;
	}
	buff = (LPBYTE)malloc(size);
	if(buff != NULL)
	{
		*lpSize = size;
		file.Read(buff, size);
	}
	file.Close();
	return buff;
}

void FreeFile(LPBYTE pData)
{
	free(pData);
}

BOOL CFileSplit::SaveFileData(INT index, LPBYTE data, UINT size)
{
	char text[32];
	CString file_name;
	CFile file;
	sprintf(text, ".part%d", index);
	file_name = m_dir + "\\" + m_base_name + text + m_ext_name;
	CreateDirectoryA(m_dir, NULL);
	BOOL ret = file.Open(file_name, CFile::modeCreate|CFile::modeReadWrite);
	if(ret)
	{
		file.Write(data, size);
		file.Close();
		return TRUE;
	}
	TRACE("index=%d, data=%p, size=%d\n", index, data, size);
	return FALSE;
}


BOOL CFileSplit::Setup(LPBYTE find, UINT find_size, INT offset)
{
	memcpy(m_find, find ,find_size);
	m_find_size = find_size;
	m_offset = offset;
	return TRUE;
}

BOOL CFileSplit::Process(LPCTSTR szInputFile, LPCTSTR szOutputDir, CFileSplitListen *pListener)
{
	int    index;
	DWORD  addr;
	DWORD  size;
	DWORD  last;
	LPBYTE file_data;
	file_data = LoadFile(szInputFile, &size);
	if(file_data == NULL)
	{
		return FALSE;
	}
	m_ext_name = PathFindExtensionA(szInputFile);
	m_base_name = PathFindFileNameA(szInputFile);
	m_dir = szOutputDir;

	last = 0;
	index = 0;
	addr = (m_offset < 0) ? (0 - m_offset) : 0;	
	size -= m_find_size;
	size -= (m_offset > 0) ? m_offset : 0;
	while(addr < size)
	{
		if(memcmp(&file_data[addr], m_find, m_find_size) == 0)
		{
			SaveFileData(index, &file_data[last], addr + m_offset - last);
			index++;
			last = addr + m_offset;
			addr += m_find_size;
		}
		else
		{
			addr += 1;
		}
	}
	SaveFileData(index, &file_data[last], addr + m_offset - last + m_find_size);
	FreeFile(file_data);
	return TRUE;
}
